package com.controller.lib.download;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.controller.lib.DmSdk;
import com.controller.lib.utils.FileUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener1;
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import timber.log.Timber;

/**
 * @author : GeRui
 * date   : 2025/6/26 10:56
 * desc   :
 * version: 1.0
 */

public class OKDownloadHelper {
  private static volatile OKDownloadHelper instance;

  private final Map<String, DownloadTask> taskMap = new HashMap<>();

  private OKDownloadHelper() {
  }

  public static OKDownloadHelper getInstance() {
    if (instance == null) {
      synchronized (OKDownloadHelper.class) {
        if (instance == null) {
          instance = new OKDownloadHelper();
        }
      }
    }
    return instance;
  }

  public void initDownloader(Context context) {
    OkDownload.Builder builder = new OkDownload.Builder(context);
    OkDownload.setSingletonInstance(builder.build());
    //OkDownload.with().downloadDispatcher().setMaxParallelRunningCount(3); // 设置最大并行下载数
  }

  /**
   * 创建下载任务
   */
  private DownloadTask createTask(String url, String parentPath, String filename) {
    if (FileUtils.Companion.isFileExists(parentPath)) {
      FileUtils.Companion.createOrExistsDir(parentPath);
    }
    if (TextUtils.isEmpty(url) || TextUtils.isEmpty(parentPath)) {
      Timber.e("URL和存储路径不能为空");
      return null;
    }

    if (TextUtils.isEmpty(filename)) {
      filename = getFilenameFromUrl(url);
    }
    return new DownloadTask.Builder(url, parentPath, filename)
        .setMinIntervalMillisCallbackProcess(800)
        .setPassIfAlreadyCompleted(false)
        .build();
  }

  /**
   * 开始下载
   */
  public void startDownload(String url, String parentPath, String filename,String md5, DownloadListener listener) {
   String filePath = parentPath + File.separator + filename;
    boolean orExistsDir = FileUtils.Companion.createOrExistsDir(parentPath);
    Timber.d("Directory exists or created: %s, Path: %s", orExistsDir, parentPath);
    if(FileUtils.Companion.isFileExists(filePath)){
      File file = new File(filePath);
      String fileMD5 = FileUtils.Companion.getFileMD5(file);
      Timber.d("File MD5: %s, Expected MD5: %s", fileMD5, md5);
      if(TextUtils.equals(fileMD5,md5)){
        Timber.d("File already exists and MD5 matches: %s", filePath);
        listener.onDownloadFinish(file, null);
        return;
      }
    }
    //删除目录下的所有文件
    FileUtils.Companion.deleteFilesInDir(parentPath);
    DownloadTask task = createTask(url, parentPath, filename);
    if (task == null) return;
    String key = task.getUrl();
    taskMap.put(key, task);
    task.enqueue(new DownloadListener1() {
      @Override public void taskStart(@NonNull DownloadTask task,
          @NonNull Listener1Assist.Listener1Model model) {
        Timber.d("Download task started: %s", task.getUrl());
      }

      @Override public void retry(@NonNull DownloadTask task, @NonNull ResumeFailedCause cause) {

      }

      @Override
      public void connected(@NonNull DownloadTask task, int blockCount, long currentOffset,
          long totalLength) {

      }

      @Override
      public void progress(@NonNull DownloadTask task, long currentOffset, long totalLength) {
        Timber.d("Download progress: %s, currentOffset: %d, totalLength: %d",
            task.getUrl(), currentOffset, totalLength);
        if (currentOffset == totalLength) {
          String fileMD5 = FileUtils.Companion.getFileMD5(task.getFile());
          Timber.d("File MD5: %s,%s", fileMD5,md5);
          if(TextUtils.equals(fileMD5,md5)){
            listener.onDownloadFinish(task.getFile(), task);
          }
        }
      }

      @Override public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause,
          @Nullable Exception realCause, @NonNull Listener1Assist.Listener1Model model) {
        Timber.d("Download task ended: %s, cause: %s, realCause: %s", task.getUrl(), cause,
            realCause);
        task.cancel();
      }
    });
  }

  /**
   * 暂停下载
   */
  public void pauseDownload(String url) {
    DownloadTask task = taskMap.get(url);
    if (task != null) {
      OkDownload.with().downloadDispatcher().cancel(task);
    }
  }

  /**
   * 获取默认下载目录
   */
  public String getDefaultDownloadPath() {
    return Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
  }

  private String getFilenameFromUrl(String url) {
    try {
      return url.substring(url.lastIndexOf('/') + 1);
    } catch (Exception e) {
      return "download_" + System.currentTimeMillis();
    }
  }

  public interface DownloadListener {
    void onDownloadFinish(File file, DownloadTask task);

    void onErrorEvent(DownloadTask task, Exception exception);
  }
}
